package com.net.xpay.clean.scheduler;

import com.net.xpay.common.domain.backup.*;
import com.net.xpay.common.manager.backup.*;
import com.net.common.util.LocalDateUtil;
import com.net.common.util.MoneyUtil;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.domain.UserShard;
import com.net.xpay.common.domain.partner.PartnerCombinationSettleRecord;
import com.net.xpay.common.domain.stat.CompanyBillDailyStat;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.common.manager.UserShardManager;
import com.net.xpay.common.manager.partner.PartnerCombinationSettleRecordManager;
import com.net.xpay.common.manager.stat.CompanyBillDailyStatManager;
import com.net.xpay.common.manager.stat.UserSafePayTransStatManager;
import com.net.xpay.common.manager.stat.UserTransStatManager;
import com.net.xpay.common.model.UserSafePayTransStatSumModel;
import com.net.xpay.common.model.UserTransStatSumModel;
import com.net.xpay.common.model.search.CompanyBillDailyStatSearchModel;
import com.net.xpay.common.model.search.UserSearchModel;
import com.net.xpay.core.domain.UserAccount;
import com.net.xpay.core.enums.AccountBillType;
import com.net.xpay.core.enums.AccountFundType;
import com.net.xpay.core.manager.AccountLogManager;
import com.net.xpay.core.manager.UserAccountManager;
import com.net.xpay.core.model.AccountLogSearchModel;
import com.net.xpay.core.model.UserSafePayTransStatSearchModel;
import com.net.xpay.core.model.UserTransStatSearchModel;
import com.net.xpay.core.utils.BeanCopierUtil;
import com.net.shard.ShardUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.util.List;

/**
 * 数据备份
 */
@Slf4j
//@Component
public class BackupScheduler {

    @Autowired
    private CompanyBillDailyStatManager companyBillDailyStatManager;

    @Autowired
    private X1Manager x1Manager;

    @Autowired
    private UserSafePayTransStatManager userSafePayTransStatManager;

    @Autowired
    private X2Manager x2Manager;

    @Autowired
    private UserManager userManager;

    @Autowired
    private UserTransStatManager userTransStatManager;

    @Autowired
    private X3Manager x3Manager;

    @Autowired
    private UserShardManager userShardManager;

    @Autowired
    private UserAccountManager userAccountManager;

    @Autowired
    private AccountLogManager accountLogManager;

    @Autowired
    private X4Manager x4Manager;

    @Autowired
    private PartnerCombinationSettleRecordManager partnerCombinationSettleRecordManager;

    @Autowired
    private X5Manager x5Manager;


    private static final LocalDate END_DAY = LocalDateUtil.parseStringToDateTime("2023-10-31 00:00:00").toLocalDate();

    /**
     * 日收益数据汇总备份
     */
    @Scheduled(cron = "0 38 18 18 2 ?")
    public void doBackupX1() {
        try {
            X1 selected = x1Manager.getById(1L);
            if (selected != null) {
                return;
            }

            CompanyBillDailyStatSearchModel searchModel = new CompanyBillDailyStatSearchModel();
            searchModel.setEndDay(END_DAY);
            CompanyBillDailyStat companyBillDailyStat = companyBillDailyStatManager.sumCompanyBillDailyStat(searchModel);
            X1 x1 = new X1();
            BeanCopierUtil.copy(companyBillDailyStat, x1);
            x1.setEndDay(END_DAY);

            x1Manager.save(x1);
            log.warn("doBackupX1 success");

        } catch (Throwable e) {
            log.warn("doBackupX1 error", e);
        }
    }

    /**
     * 商户安全发转账数据汇总备份
     */
    @Scheduled(cron = "0 46 18 18 2 ?")
    public void doBackupX2() {
        try {
            //先查出用户
            UserSearchModel userSearchModel = new UserSearchModel();
            userSearchModel.setPageSize(10000L);
            userSearchModel.setMaxRegisterTime(LocalDateUtil.getDayEnd(END_DAY));
            List<User> userList = userManager.search(userSearchModel);
            for (User user : userList) {
                UserSafePayTransStatSearchModel searchModel = new UserSafePayTransStatSearchModel();
                searchModel.setUserId(user.getId());
                searchModel.setMaxDay(END_DAY);
                UserSafePayTransStatSumModel userSafePayTransStatSumModel = userSafePayTransStatManager.sumUserSafePayTransStat(searchModel);
                X2 x2 = new X2();
                BeanCopierUtil.copy(userSafePayTransStatSumModel, x2);
                x2.setUserId(user.getId());
                x2.setEndDay(END_DAY);
                x2.setPartnerId(user.getPartnerId());
                x2.setServiceRatio(user.getServiceRatio());
                x2.setBankServiceRatio(user.getBankServiceRatio());
                x2Manager.save(x2);
            }

            log.warn("doBackupX2 success");
        } catch (Throwable e) {
            log.warn("doBackupX2 error", e);
        }
    }


    /**
     * 商户批量有密转账数据汇总备份
     */
    @Scheduled(cron = "0 38 18 18 2 ?")
    public void doBackupX3() {
        try {
            //先查出用户
            UserSearchModel userSearchModel = new UserSearchModel();
            userSearchModel.setPageSize(10000L);
            userSearchModel.setMaxRegisterTime(LocalDateUtil.getDayEnd(END_DAY));
            List<User> userList = userManager.search(userSearchModel);
            for (User user : userList) {
                UserTransStatSearchModel searchModel = new UserTransStatSearchModel();
                searchModel.setUserId(user.getId());
                searchModel.setMaxDay(END_DAY);
                UserTransStatSumModel userSafePayTransStatSumModel = userTransStatManager.sumUserSafePayTransStat(searchModel);
                X3 x3 = new X3();
                BeanCopierUtil.copy(userSafePayTransStatSumModel, x3);
                x3.setUserId(user.getId());
                x3.setEndDay(END_DAY);
                x3.setPartnerId(user.getPartnerId());
                x3.setMode(user.getMode());
                x3.setServiceRatio(user.getServiceRatio());
                x3.setServiceUnitPrice(user.getServiceUnitPrice());
                x3Manager.save(x3);
            }

            log.warn("doBackupX3 success");
        } catch (Throwable e) {
            log.warn("doBackupX3 error", e);
        }
    }


    /**
     * 商户服务费数据汇总备份
     */
    @Scheduled(cron = "0 5 19 18 2 ?")
    public void doBackupX4() {
        try {
            //先查出用户
            UserSearchModel userSearchModel = new UserSearchModel();
            userSearchModel.setPageSize(10000L);
            userSearchModel.setMaxRegisterTime(LocalDateUtil.getDayEnd(END_DAY));
            List<User> userList = userManager.search(userSearchModel);
            for (User user : userList) {
                UserShard userShard = userShardManager.getById(user.getId());
                X4 x4 = new X4();
                x4.setUserId(user.getId());
                x4.setPartnerId(user.getPartnerId());
                try {
                    ShardUtil.setShardContext(userShard.getShardId());
                    UserAccount userAccount = userAccountManager.getById(user.getId());
                    x4.setLeftMoney(MoneyUtil.convertCentToBigDecimal(userAccount.getMoneyLeft(), 2));

                    //充值金额
                    AccountLogSearchModel searchModel = new AccountLogSearchModel();
                    searchModel.setUserId(user.getId());
                    searchModel.setCreateMaxTime(LocalDateUtil.getDayStart(END_DAY.plusDays(1L)));
                    searchModel.setAccountFundType(AccountFundType.MONEY);

                    searchModel.setType(AccountBillType.CHARGE);

                    long chargeAmount = accountLogManager.sumAccountLog(searchModel);
                    searchModel.setType(AccountBillType.CANCEL_CHARGE);
                    long cancelChargeAmount = accountLogManager.sumAccountLog(searchModel);

                    chargeAmount = chargeAmount + cancelChargeAmount;

                    x4.setChargeAmount(MoneyUtil.convertCentToBigDecimal(chargeAmount, 2));

                    //安全发消费金额
                    searchModel.setType(AccountBillType.SAFE_PAY_TRANS_SERVICE_PRICE);
                    long safePayTransServicePrice = accountLogManager.sumAccountLog(searchModel);
                    searchModel.setType(AccountBillType.SAFE_PAY_TRANS_SERVICE_PRICE_REFUND);
                    long safePayTransServicePriceRefund = accountLogManager.sumAccountLog(searchModel);
                    x4.setSafePayTransServicePrice(MoneyUtil.convertCentToBigDecimal(-(safePayTransServicePrice + safePayTransServicePriceRefund), 2));

                    //批量有密消费金额
                    searchModel.setType(AccountBillType.PAY_TRANS_SERVICE_PRICE);
                    long payTransServicePrice = accountLogManager.sumAccountLog(searchModel);
                    searchModel.setType(AccountBillType.PAY_TRANS_SERVICE_PRICE_REFUND);
                    long payTransServicePriceRefund = accountLogManager.sumAccountLog(searchModel);
                    x4.setPayTransServicePrice(MoneyUtil.convertCentToBigDecimal(-(payTransServicePrice + payTransServicePriceRefund), 2));

                    //安全付验证码消费金额
                    searchModel.setType(AccountBillType.CHECK_CODE);
                    long checkCodeServicePrice = accountLogManager.sumAccountLog(searchModel);
                    x4.setCheckCodeServicePrice(MoneyUtil.convertCentToBigDecimal(-checkCodeServicePrice, 2));

                    //服务费退款金额
                    searchModel.setType(AccountBillType.USER_WITHDRAW_REFUND);
                    long userWithdrawRefund = accountLogManager.sumAccountLog(searchModel);
                    searchModel.setType(AccountBillType.USER_WITHDRAW_FAIL);
                    long userWithdrawFail = accountLogManager.sumAccountLog(searchModel);
                    x4.setUserWithdrawRefund(MoneyUtil.convertCentToBigDecimal(-(userWithdrawRefund + userWithdrawFail), 2));

                    x4Manager.save(x4);
                } finally {
                    ShardUtil.cleanShardContext();
                }
            }

            log.warn("doBackupX4 success");
        } catch (Throwable e) {
            log.warn("doBackupX4 error", e);
        }
    }

    /**
     * 合伙人收益数据汇总备份
     */
    @Scheduled(cron = "0 38 18 18 2 ?")
    public void doBackup5() {
        try {
            //先查出用户
            UserSearchModel userSearchModel = new UserSearchModel();
            userSearchModel.setPageSize(10000L);
            userSearchModel.setMaxRegisterTime(LocalDateUtil.getDayEnd(END_DAY));
            List<User> userList = userManager.search(userSearchModel);
            for (User user : userList) {
                if (user.getPartnerId() == null) {
                    continue;
                }

                //商户月数据
                List<PartnerCombinationSettleRecord> settleRecords = partnerCombinationSettleRecordManager.aggSumUserMonthData(user.getId(),  END_DAY);
                List<X5> x5s = BeanCopierUtil.batchCopy(PartnerCombinationSettleRecord.class, X5.class, settleRecords);

                for (X5 x5 : x5s) {
                    x5Manager.save(x5);
                }
            }

            log.warn("doBackupX5 success");
        } catch (Throwable e) {
            log.warn("doBackupX5 error", e);
        }
    }


}
